package com.lemon.components.baidu.ocr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.aip.ocr.AipOcr;
import com.lemon.components.baidu.BaiduBase;
import com.lemon.components.baidu.voice.BaiduVoice;

public class BaiduOcr extends BaiduBase {

	public String ocr(String imgPath){
		StringBuilder sb = new StringBuilder();
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
    	JSONObject res = client.basicGeneral(imgPath, new HashMap<String, String>());
    	try {
    		JSONArray jsonArray = res.getJSONArray("words_result");
    		for(int start =0 ; start < jsonArray.length();start ++){
    			JSONObject obj = jsonArray.getJSONObject(start);
    			sb.append(obj.getString("words"));
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return sb.toString();
	}
	
	public void ocrSpeek(String imgPath){
    	String tmp = ocr(imgPath);
    	BaiduVoice voice = new BaiduVoice();
    	
    	List<String> list = getStrList(tmp,500);
    	for(String test:list){
    		voice.speek(test);
    	}
	}
	
	public List<String> getStrList(String inputString, int length) {
        int size = inputString.length() / length;
        if (inputString.length() % length != 0) {
            size += 1;
        }
        return getStrList(inputString, length, size);
    }
    
    public List<String> getStrList(String inputString, int length,
            int size) {
        List<String> list = new ArrayList<String>();
        for (int index = 0; index < size; index++) {
            String childStr = substring(inputString, index * length,
                    (index + 1) * length);
            list.add(childStr);
        }
        return list;
    }
    
    public String substring(String str, int f, int t) {
        if (f > str.length())
            return null;
        if (t > str.length()) {
            return str.substring(f, str.length());
        } else {
            return str.substring(f, t);
        }
    }
    
    public static void main(String[] args) {
    	BaiduOcr baiduOcr = new BaiduOcr();
    	System.out.println(baiduOcr.ocr("D:\\20190116101936.jpg"));
	}
}
